//
//  SCPasterView.m
//  CATransform3DDemo
//
//  Created by liyanan on 2019/10/15.
//  Copyright © 2019 shuaiche. All rights reserved.
//

#import "SCPasterView.h"
#import <UIButton+WebCache.h>
#import <UIImageView+WebCache.h>
#import "UIImageView+SCwebImage.h"

#define padding 0.0
@interface SCPasterView()
@property (nonatomic, assign) CGPoint touchStart;
@property (nonatomic, assign) BOOL firstShow;

/////

@end

@implementation SCPasterView

- (instancetype)init {
    self = [super init];
    if (self) {
        _firstShow = YES;
        self.userInteractionEnabled = YES;
        self.layer.anchorPoint = CGPointZero;
//        self.layer.borderColor = SC_RGB(255, 156, 0).CGColor;
//        self.layer.borderWidth = 1.0;
    }
    return self;
}
- (void)setPasterImagePath:(NSString *)pasterImagePath {
    if ([_pasterImagePath isEqualToString:pasterImagePath]) {
        return;
    }
    _pasterImagePath = pasterImagePath;
    if (_firstShow) {
        _firstShow = NO;
        [self resizeFrameByWidth:110];
    }
    WEAKSELF
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:sc_url_img(pasterImagePath)] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [weakSelf setPasterImage:image];
    }];
}

-(void)setPasterImage:(UIImage * _Nullable)pasterImage {
    CGFloat w = pasterImage.size.width;
    CGFloat h = pasterImage.size.height;
    const CGRect rect = CGRectMake(0, 0, 220, 66);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGRect clipRect = h/w <= 0.3 ? CGRectMake(0, 0, ceilf(h*3.33), h) : CGRectMake(0, 0, w, ceilf(w*0.3));
    CGImageRef newImageRef = CGImageCreateWithImageInRect(pasterImage.CGImage, clipRect);
    CGContextDrawImage(context, rect, newImageRef);
    UIImage *sizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    _pasterImage = sizeImage;
    self.imageView.image = _pasterImage;
}
- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.tag = 1000;
        _imageView.layer.anchorPoint = CGPointZero;
        [self addSubview:_imageView];
    }
    return _imageView;
}

- (void)resizeFrameByWidth:(CGFloat)w {
    CGFloat h = ceilf(w * 0.3);
    self.imageView.frame = CGRectMake(padding, padding, w, h);
    self.bounds = CGRectMake(0,0, w , h);
}

#pragma mark- Move
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    UITouch *touch = [touches anyObject] ;
    _touchStart = [touch locationInView:self.superview];
     if ([_delegate respondsToSelector:@selector(pasterViewTouchBegin)]) {
         [_delegate pasterViewTouchBegin];
     }
}
/**
 *  移动
 */
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
//    CGPoint touchLocation = [[touches anyObject] locationInView:self];
//    if (CGRectContainsPoint(self.frame, touchLocation)) {
//        return;
//    }
    CGPoint touch = [[touches anyObject] locationInView:self.superview];
//    [self checkIsOut];

    [self translateUsingTouchLocation:touch];
    _touchStart = touch;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if ([_delegate respondsToSelector:@selector(pasterViewTouchEnd)]) {
        [_delegate pasterViewTouchEnd];
    }
}

/**
  *  检查在添加tag的时候是否超出了显示范围，如果超出，移动进显示范围内
  */
- (void)checkIsOut {
    CGPoint point = self.center;
    CGFloat top;
    CGFloat left;
    CGFloat bottom;
    CGFloat right;
    top = point.y - self.frame.size.height/2;
    bottom = (self.superview.frame.size.height - point.y) - self.frame.size.height/2;
    
    //顶部超出范围时
    if (point.y < self.superview.frame.size.height/2) {
        if (top < 0) {
            point.y += ABS(top);
        }
    } else  { //底部超出范围时
        if (bottom < 0) {
            point.y -= ABS(bottom);
        }
    }
    
    left = point.x - self.frame.size.width/2;
    right =(self.superview.frame.size.width - point.x) - self.frame.size.width/2;
    if (point.x < self.superview.frame.size.width/2) { //左边超出范围时
        if (left < 0) {
            point.x += ABS(left);
        }
    }
    else {//右边超出范围时
        if (right < 0) {
            point.x -= ABS(right);
        }
    }
    
    if (point.x == self.center.x && point.y == self.center.y) {
    }else{
        [UIView animateWithDuration:0.2 animations:^{
            self.center = point;
        }];
    }
}

/**
 *  确保移动时不超出屏幕
 */
- (void)translateUsingTouchLocation:(CGPoint)touchPoint
{
    CGPoint point = CGPointMake( touchPoint.x - _touchStart.x, touchPoint.y - _touchStart.y);
//    CGPoint newCenter = CGPointMake(self.center.x + point.x,self.center.y + point.y) ;
//    self.center = newCenter;
    if ([_delegate respondsToSelector:@selector(pasterViewDidMovedWithPoint:)]) {
        [_delegate pasterViewDidMovedWithPoint:point];
    }
}
@end
